<template>
  <div class="search">
    <div class="search_input">
      <van-search
        ref="search"
        v-model="keywords"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </div>
    <div class="hotkws">
      <h3>热门搜索</h3>
      <span @click="hotkwEvent(kw.title)" v-for="kw in hotkws" :key="kw.id">{{
        kw.title
      }}</span>
    </div>
    <div class="results" v-if="results">
      <img
        v-if="results.length === 0"
        src="https://java.crmeb.net/static/img/noSearch.73260101.png"
        alt=""
      />
      <div class="result" v-else>
        <div class="result_item" v-for="r in results" :key="r.id">
          {{ r.storeName }}
        </div>
      </div>
    </div>
    <hot-search v-show="!results || results.length === 0" />
  </div>
</template>

<script>
import HotSearch from "@/components/HotSearch.vue";
export default {
  name: "Vue2FxhSearch",
  data() {
    return {
      keywords: "",
      hotkws: [],
      results: null,
    };
  },
  created() {
    this.$axios
      .get("https://apif.java.crmeb.net/api/front/search/keyword")
      .then(({ data }) => {
        this.hotkws = data.data;
      });
  },
  mounted() {
    // 组件自动聚焦.
    this.$refs.search.getElementsByClassName("van-field__control")[0].focus();
  },
  methods: {
    onSearch() {
      if (this.keywords) {
        this.$axios
          .get(
            `https://apif.java.crmeb.net/api/front/products?keyword=${this.keywords}&page=1&limit=8`
          )
          .then(({ data }) => {
            this.results = data.data.list;
          });
      } else {
        alert("请输入关键字");
      }
    },
    onCancel() {
      console.log("取消");
    },
    hotkwEvent(title) {
      this.keywords = title;
      this.onSearch();
    },
  },
  components: {
    HotSearch,
  },
};
</script>

<style lang="scss" scoped>
.hotkws {
  margin: 10px 0;
  span {
    margin: 0 10px;
    margin-top: 10px;
  }
}
.results {
  img {
    width: 207px;
    height: 168px;
  }
  .result_item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    height: 40px;
    line-height: 40px;
    padding-left: 10px;
  }
}
</style>
